/*
 * Copyright 2008 Georgi Staykov
 * 
 * This file is part of pscoder.
 *
 * pscoder is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * pscoder is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with pscoder.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.gstaykov.pscoder.editor.handlers;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.Path;
import org.eclipse.jface.text.TextSelection;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.ui.IEditorDescriptor;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.part.FileEditorInput;
import org.eclipse.ui.texteditor.ITextEditor;

import com.gstaykov.pscoder.editor.completion.CompletionDictionary;
import com.gstaykov.pscoder.util.Logger;
import com.gstaykov.pscoder.util.Util;

public class GoToDefinitionHandler extends AbstractHandler {

    private Logger logger = Logger.getInstance();
    
    public Object execute(ExecutionEvent event) throws ExecutionException {
        ISelection selection = ((ITextEditor)Util.getActiveEditor()).getSelectionProvider().getSelection();
        TextSelection tselection = null;
        if (selection instanceof TextSelection) {
            tselection = (TextSelection)selection;
        } else {
            return null;
        }
        
        String functionName = getWord(Util.getActiveDocument(event).get(), tselection.getOffset());
        ITextEditor targetEditor = null;
        try {
            CompletionDictionary dict = CompletionDictionary.getInstance(Util.getActiveFile().getProject().getName());
            String fileName = dict.getFileData(Util.getActiveFile().getLocation().toFile().getAbsolutePath()).getFunctionOwner(functionName, dict);
            if (fileName == null)
                return null;
            targetEditor = (ITextEditor)openEditor(fileName);
        } catch (CoreException ce) {
            logger.logError("Error while trying to get Completion dictionary object", ce);
        }
        
        if (targetEditor != null) {
            int offset = Util.getActiveDocument(event).get().indexOf(functionName + "(");
            targetEditor.setHighlightRange(offset, functionName.length(), true);
        }
        
        return null;
    }
    
    private String getWord(String document, int offset) {
        int startIndex = offset;
        int endIndex = offset;
        while (Character.isLetterOrDigit(document.charAt(startIndex))) startIndex--;
        while (Character.isLetterOrDigit(document.charAt(endIndex))) endIndex++;
        startIndex++;
        
        return document.substring(startIndex, endIndex);
    }
    
    private IEditorPart openEditor(String fileName) {
        IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
        IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
        IFile files[] = root.findFilesForLocation(new Path(fileName));
        if (files.length != 0) {
            IEditorDescriptor desc = PlatformUI.getWorkbench().getEditorRegistry().getDefaultEditor(files[0].getName());
            try {
                return page.openEditor(new FileEditorInput(files[0]), desc.getId());
            } catch (PartInitException pie) {
                logger.logError("Unable to open new editor", pie);
            }
        }
        
        return null;
    }
}
